import { acceptHMRUpdate, defineStore } from 'pinia';

import { ENV_CONFIG } from '#/config/env';

export interface SiteInfo {
  siteId: number;
  siteName: string;
  siteDomain?: string;
  groupId: number;
  groupName: string;
  status: number;
  statusName: string;
}

export interface ShopAuthInfo {
  token: string;
  expires_time: number; // 后端返回的字段名
  userinfo: any;
  site_id: number; // 后端返回的字段名
  site_info: any; // 后端返回的字段名
  userrole: any;
}

interface SiteState {
  /**
   * 当前选中的站点ID
   */
  currentSiteId: null | number;
  /**
   * 当前选中的站点信息
   */
  currentSiteInfo: null | SiteInfo;
  /**
   * Shop认证信息
   */
  shopAuthInfo: null | ShopAuthInfo;
}

/**
 * 站点管理相关
 */
export const useSiteStore = defineStore('site', {
  actions: {
    /**
     * 设置当前站点ID
     */
    setCurrentSiteId(siteId: number) {
      this.currentSiteId = siteId;
    },

    /**
     * 设置当前站点信息
     */
    setCurrentSiteInfo(siteInfo: SiteInfo) {
      this.currentSiteInfo = siteInfo;
      this.currentSiteId = siteInfo.siteId;
    },

    /**
     * 获取当前站点ID
     */
    getCurrentSiteId(): null | number {
      return this.currentSiteId;
    },

    /**
     * 获取当前站点信息
     */
    getCurrentSiteInfo(): null | SiteInfo {
      return this.currentSiteInfo;
    },

    /**
     * 跳转到站点管理页面
     */
    navigateToSite(siteId?: number) {
      const targetSiteId = siteId || this.currentSiteId;
      if (targetSiteId) {
        // 设置站点ID到store，然后跳转（不显示在URL中）
        this.setCurrentSiteId(targetSiteId);
        window.open(ENV_CONFIG.SITE_URL, '_blank');
      } else {
        window.open(ENV_CONFIG.SITE_URL, '_blank');
      }
    },

    /**
     * 设置Shop认证信息
     */
    setShopAuthInfo(authInfo: ShopAuthInfo) {
      this.shopAuthInfo = authInfo;
    },

    /**
     * 获取Shop认证token
     */
    getShopAuthToken(): null | string {
      return this.shopAuthInfo?.token || null;
    },

    /**
     * 获取Shop认证信息
     */
    getShopAuthInfo(): null | ShopAuthInfo {
      return this.shopAuthInfo;
    },

    /**
     * 检查Shop认证是否有效
     */
    isShopAuthValid(): boolean {
      if (!this.shopAuthInfo) return false;
      // 后端返回的是Unix时间戳（秒），需要转换为毫秒
      return Date.now() < this.shopAuthInfo.expires_time * 1000;
    },

    /**
     * 清除当前站点信息
     */
    clearCurrentSite() {
      this.currentSiteId = null;
      this.currentSiteInfo = null;
      this.shopAuthInfo = null;
    },
  },
  persist: {
    // 持久化存储
    pick: ['currentSiteId', 'currentSiteInfo', 'shopAuthInfo'],
  },
  state: (): SiteState => ({
    currentSiteId: null,
    currentSiteInfo: null,
    shopAuthInfo: null,
  }),
});

// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
  hot.accept(acceptHMRUpdate(useSiteStore, hot));
}
